<template>
  <div class="user-info-card">
    <div class="card">
      <el-button text @click="toUserInfo" class="back">
        <el-icon><Back /></el-icon>
      </el-button>
      <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:8888/upload/avatar"
          :headers="{'token':token}"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="ruleForm"
      >
        <el-form-item label="名字" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入名字"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleForm.gender" class="ml-4">
            <el-radio value="男" size="large">男</el-radio>
            <el-radio value="女" size="large">女</el-radio>
            <el-radio value="未知" size="large">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="个人介绍" prop="bio">
        <el-input
            v-model="ruleForm.bio"
            style="width: 240px"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            max="200"
            placeholder="个人介绍"
        />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue';
import { useRoute } from 'vue-router';
import {getTokenWithExpiration} from '@/components/cookie';

const route = useRoute();
const userId = ref(route.params.userid);

const token = ref(getTokenWithExpiration())

import {ElMessage, type FormInstance, type FormRules} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'

const imageUrl = ref()


const ruleFormRef = ref<FormInstance>()


const email = (rule: any, value: any, callback: any) => {
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (ruleForm.email !==""){
    if (!emailRegex.test(ruleForm.email)){
      callback(new Error("邮箱格式错误"))
    }
  }
    callback()
}

const name = (rule: any, value: any, callback: any) => {

    if (value.length>8) {
      callback(new Error("名字超过8位"))
    }
    callback()
}

const bio = (rule: any, value: any, callback: any) => {
    if (value.length>200) {
      callback(new Error("不能超过200字"))
    }
    callback()
}


const ruleForm = reactive({
  gender: '',
  bio: '',
  email:'',
  name:'',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  email: [{ validator: email, trigger: 'blur' }],
  name: [{ validator: name, trigger: 'blur' }],
})


import {login, updateUserInfo} from "@/http/api";
import router from "@/router";

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      updateUserInfo({
        "gender": ruleForm.gender,
        "bio": ruleForm.bio,
        "email": ruleForm.email,
        "name": ruleForm.name,
      "uid": userId.value,}).then((res)=>{
          if (res.code === 10000){
            ElMessage.success("修改成功")
          }else {
            ElMessage.error("修改失败")
          }
      })
    } else {
      return false
    }
  })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  console.log(response)
  if (response.code ===10000){
    ElMessage.success('头像上传成功')
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  }else {
    ElMessage.error('头像上传失败')
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是jpg/png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage.error('图片不能超过3M')
    return false
  }
  return true
}

function toUserInfo(){
  router.push('/userinfo/'+userId.value)
}

</script>

<style>
.back{
  width: 30px;
  margin-left: 0px;
  margin-bottom: 40px;
}

.user-info-card {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 615px;
}

.card {
  width: 60vw;
  height: 60vh;
  padding: 50px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.16);

}

.avatar img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 15px;
}


</style>

<style scoped>
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>